#! python
# -*- coding: utf-8 -*-

import functools
import json
from .config import redis_client


class ProgressBarManager(object):

    def __init__(self, cache):
        self.cache_client = cache
        self.base_key = "progress_bar::%s"

    def set_progress_bar(self, key, progress, url="", msg=None, errormsg=None, timeout=600):
        """
        @desc 更新进度条
        :param key: 进度条的key
        :param progress: 进度， 大于0小于10的整数
        :param url: 下载链接，在progress等于100时返回
        :param msg: 正常下载信息
        :param errormsg: 下载错误信息
        :param timeout: 超时时间
        :return:
        """
        if not key:
            return
        progress_key = self.base_key % key
        bar = self.cache_client.get(progress_key)
        if bar:
            bar_data = json.loads(bar)
            current_progress = bar_data["progress"]
            if str(current_progress) == "100":
                return

        if not isinstance(progress, int):
            return
        progress = 0 if progress < 0 else 100 if progress > 100 else progress

        data = {"progress": progress, 'url': url, 'msg': msg, 'errormsg': errormsg}

        self.cache_client.set(progress_key, json.dumps(data), timeout)

    def get_progress_bar(self, key):
        """
        @desc 获取进度条
        :param key:
        :return:
        """
        if not key:
            return {}, 0
        bar = self.cache_client.get(self.base_key % key)
        if bar:
            return json.loads(bar), self.cache_client.ttl(self.base_key % key)
        else:
            return {}, 0

    def progress_bar(self, key, progress, timeout=600):
        """
        @desc 进度条装饰器
        :param key:
        :param progress:
        :param timeout:
        :return:
        """

        def base_progress_bar(func):
            @functools.wraps(func)
            def decorated_function(*args, **kwargs):
                res = func(*args, **kwargs)
                self.set_progress_bar(key=key, progress=progress, msg=None, errormsg=None, timeout=timeout)
                return res

            return decorated_function

        return base_progress_bar


bar_manager = ProgressBarManager(redis_client)
